const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const userRoutes = require('./routes/userRoutes');
const sequelize = require('./config/database');
const initDatabase = require('./config/initDb');

const app = new Koa();

// 中间件
app.use(bodyParser());

// 路由
app.use(userRoutes.routes());
app.use(userRoutes.allowedMethods());

// 错误处理
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        ctx.status = err.status || 500;
        ctx.body = {
            code: err.status || 500,
            errMsg: err.message
        };
    }
});

const PORT = process.env.PORT || 3000;

// 数据库同步并启动服务器
sequelize.sync({ force: true }).then(async () => {
    console.log('数据库已同步');
    
    // 初始化数据库
    await initDatabase();
    
    app.listen(PORT, () => {
        console.log(`服务器运行在 http://localhost:${PORT}`);
    });
}).catch(err => {
    console.error('数据库同步失败:', err);
}); 